package com.irs.irsforum.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.type.TypeFactory;

import java.io.IOException;
import java.util.List;
/**
 * @author Liyihui
 * @Date: 2020/3/22
 * @Time: 3:09
 */
public class JsonUtil {

    private static final ObjectMapper GLOBALMAPPER = new ObjectMapper();

    public static ObjectMapper getGlobalMapper() {
        return GLOBALMAPPER;
    }

    public static String toJsonString(Object object) throws JsonProcessingException {
        return GLOBALMAPPER.writeValueAsString(object);
    }

    public static ObjectNode createObjectNode() {
        return GLOBALMAPPER.createObjectNode();
    }

    public static ArrayNode createArrayNode() {
        return GLOBALMAPPER.createArrayNode();
    }

    public static JsonNode toJsonNode(String jsonString) throws IOException {
        return GLOBALMAPPER.readTree(jsonString);
    }

    public static JsonNode obj2JsonNode(Object javaObject) throws IOException {
        return GLOBALMAPPER.readTree(toJsonString(javaObject));
    }

    public static <T> T deserialze(String jsonString, Class<T> clazz) throws IOException {
        return GLOBALMAPPER.readValue(jsonString, clazz);
    }

    public static <T> List<T> deserialzeList(String jsonString, Class<T> clazz) throws IOException {
        return GLOBALMAPPER.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, clazz));
    }
}
